<template>
  <div id="main" class="banner">
    <main>
      <div class="x_y_center mt-20">
        <van-image
          round
          width="3rem"
          height="3rem"
          :src="data.avatarUrl"
          fit="cover"
          @click="actionShow = true"
        >
          <template v-slot:loading>
            <div class="errImgMsg x_y_center" @click.stop="dialogShow = true">
              未登录
            </div>
          </template>
        </van-image>
      </div>
      <div v-if="data.nickname" class="x_y_center mt-5 nickname">
        {{ data.nickname }}
        <van-tag
          plain
          type="primary"
          class="ml-5"
          @click="copyText(data.nickname)"
        >
          复制
        </van-tag>
      </div>
      <van-cell-group inset class="mt-20" size="large">
        <van-grid :column-num="3" class="iconThree">
          <van-grid-item icon="like" class="likes" :text="data.likes + ' 赞'" />
          <van-grid-item
            icon="smile-o"
            class="smile"
            :text="data.smile + ' 关注'"
            @click="followList('smile')"
          />
          <van-grid-item
            icon="friends-o"
            class="friends"
            :text="data.friends + ' 粉丝'"
            @click="followList('friends')"
          />
        </van-grid>
        <van-cell icon="thumb-circle" title="点赞" is-link to="index" />
        <van-cell icon="star" title="收藏" is-link to="index" />
        <van-cell icon="comment-circle" title="评论" is-link to="index" />
        <van-cell icon="todo-list" title="历史浏览" is-link to="index" />
        <van-cell icon="setting" title="设置" is-link to="index" />
        <van-cell icon="question" title="关于" is-link to="index" />
      </van-cell-group>
    </main>
    <!-- 头像点击 -->
    <van-action-sheet
      v-model:show="actionShow"
      close-on-click-action
      cancel-text="取消"
      style="z-index:2021;"
      :actions="actions"
      @select="onActions"
    />
    <!-- 注册登录框 没有就注册，有就登录 -->
    <van-dialog
      v-model:show="dialogShow"
      title="登录"
      :showConfirmButton="false"
    >
      <van-form @submit="onSubmit" label-width="60px" show-error>
        <van-cell-group inset>
          <van-field
            v-model="form.username"
            name="用户名"
            label="用户名"
            placeholder="请输入用户名"
            maxlength="10"
            :rules="[{ required: true, message: '' }]"
          />
          <van-field
            v-model="form.password"
            type="password"
            name="密码"
            label="密码"
            placeholder="请输入密码"
            maxlength="16"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            size="small"
          >
            登录
          </van-button>
          <div class="x_y_between tips">
            <span class="register">没有账号/注册一个</span>
            <span class="register password">忘记密码</span>
          </div>
        </div>
      </van-form>
    </van-dialog>
  </div>
</template>

<script>
import { onMounted, reactive, toRefs } from "vue";
import { ImagePreview, Toast } from "vant";
import { api, use } from "@/api/api.js";
import axios from "axios";
import { useRouter } from "vue-router";
//引入组件
export default {
  name: "user",
  props: {},
  components: {},
  setup() {
    let router = useRouter();
    const state = reactive({
      form: {
        username: "",
        password: "",
      },
      data: {
        email: null,
        userId: null,
        username: null,
        avatarUrl: null,
        nickname: null,
        likes: 0,
        smile: 0,
        friends: 0,
      },
      dialogShow: false,
      actionShow: false,
      actions: [
        { name: "查看头像", id: "look" },
        { name: "更换头像", id: "edit" },
        { name: "退出登录", id: "loginOut" },
      ],
    });
    // 图片预览
    const vanImagePreview = (img) => {
      ImagePreview({
        images: [img],
        overlayStyle: {
          zIndex: 9999,
        },
      });
    };
    // 用户信息
    const userInfo = async () => {
      const { data: res } = await use.get();
      if (res.status == 401) return
      if (res.status != 0) return Toast.fail(res.message);
      localStorage.setItem("user", JSON.stringify(res.data));
      state.data = res.data;
    };
    // 登录
    const onSubmit = async () => {
      // 获取ip地址
      const { data: Ip } = await axios.get("https://api.ipify.org", {
        format: "json",
      });
      const { data: res } = await api.login({ ...state.form, Ip });
      if (res.status != 0) return Toast.fail(res.message);
      localStorage.setItem("blogToken", res.token);
      userInfo();
      state.dialogShow = false;
      Toast.success("登录成功");
    };
    // 初始化加载
    onMounted(() => {
      userInfo();
    });
    // copy
    const copyText = (val) => {
      let copy = (e) => {
        e.preventDefault();
        e.clipboardData.setData("text/plain", val); // 调用window自带的剪贴板
      };
      document.addEventListener("copy", copy);
      document.execCommand("Copy");
      Toast("复制成功\n昵称: " + val);
    };
    // 动作弹窗
    const onActions = (item) => {
      console.log(item);
      if (item.id == "look") return vanImagePreview(state.data.avatarUrl); // 查看头像
      if (item.id == "loginOut") {
        // 退出登录
        localStorage.removeItem("blogToken");
        location.reload();
        Toast.success("退出登录成功");
      }
      // 默认情况下点击选项时不会自动收起
      state.actionShow = false;
    };
    const followList = (type) => {
      router.push({
        path: "/followList",
        query: {
          type: type,
        },
      });
    };
    return {
      ...toRefs(state),
      vanImagePreview,
      onSubmit,
      userInfo,
      copyText,
      onActions,
      followList,
    };
  },
};
</script>

<style lang="less" scoped>
.banner {
  background: url(https://e.im5i.com/2021/09/18/Xjm0B.jpg) no-repeat;
  height: calc(100vh - 1.3333rem);
  overflow-y: auto;
  .errImgMsg {
    height: 100%;
    width: 100%;
  }
  .nickname {
    font-size: 20px;
    font-weight: 700;
    font-family: "楷体";
  }
  /deep/.iconThree {
    .likes i {
      color: #ee0a24;
    }
    .smile i {
      color: #ff976a;
    }
    .friends i {
      color: #ff6034;
    }
  }
}
.tips {
  padding: 0 10px;
  .register {
    color: #797979;
    font-size: 10px;
    margin-top: 5px;
  }
  .password {
    color: #1989fa;
  }
}
</style>
